/**
 * @author Alfred Wang
 * @note 用于向控制台与日志文件输出日志，包括错误信息与行为记录
 */

package team.wh1tegive.misc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Log {
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static final File log = new File("./" + sdf.format(new Date()) + ".log");
    private static FileOutputStream fos = null;

    static {
        try {
            fos = new FileOutputStream(log, true);
        } catch (FileNotFoundException e) {
            Date date = new Date();
            System.out.println("[" + simpleDateFormat.format(date) + "] Cannot Write Logs.");
            System.exit(-1);
        }
    }

    public static void writeLog(String info) {
        Date date = new Date();
        String log = "[" + simpleDateFormat.format(date) + "] " + info;
        System.out.println(log);
        try {
            fos.write(log.getBytes());
            fos.write((byte) '\n');
        } catch (IOException e) {
            System.out.println("[" + simpleDateFormat.format(date) + "] Cannot Write Logs.");
            System.exit(-1);
        }
    }

    public static void writeError(String error) {
        Date date = new Date();
        String err = "[" + simpleDateFormat.format(date) + "] " + error;
        System.err.println(err);
        try {
            fos.write(err.getBytes());
            fos.write((byte) '\n');
        } catch (IOException e) {
            System.out.println("[" + simpleDateFormat.format(date) + "] Cannot Write Logs.");
            System.exit(-1);
        }
    }
}
